<template>
  <div class="login-wrapper">
    <div class="login-container">
      <div class="login-left">
        <div class="welcome-section">
          <h1>欢迎回到 AlphaExam</h1>
          <p>基于AI技术的智能考试平台，让考试更智能、更高效、更公平</p>
          <div class="features-preview">
            <div class="feature-item">
              <div class="feature-icon">🤖</div>
              <span>AI智能阅卷</span>
            </div>
            <div class="feature-item">
              <div class="feature-icon">📊</div>
              <span>数据分析</span>
            </div>
            <div class="feature-item">
              <div class="feature-icon">🔒</div>
              <span>安全监考</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="login-right">
        <div class="login-form-container">
          <div class="login-header">
            <h2>登录账户</h2>
            <p>请输入您的登录信息</p>
          </div>
          
          <form @submit.prevent="handleLogin" class="login-form">
            <div class="form-group">
              <label for="username">用户名</label>
              <div class="input-wrapper">
                <span class="input-icon">👤</span>
                <input 
                  v-model="username" 
                  id="username" 
                  type="text" 
                  placeholder="请输入用户名" 
                  required 
                />
              </div>
            </div>
            
            <div class="form-group">
              <label for="password">密码</label>
              <div class="input-wrapper">
                <span class="input-icon">🔑</span>
                <input 
                  v-model="password" 
                  id="password" 
                  type="password" 
                  placeholder="请输入密码" 
                  required 
                />
              </div>
            </div>
            
            <div class="form-options">
              <el-checkbox v-model="rememberMe">记住我</el-checkbox>
              <a href="#" class="forgot-password">忘记密码？</a>
            </div>
            
            <button type="submit" :disabled="loading" class="login-button">
              <span v-if="!loading">登 录</span>
              <span v-else class="loading-spinner">登录中...</span>
            </button>
            
            <div class="divider">
              <span>或</span>
            </div>
            
            <div class="social-login">
              <button type="button" class="social-btn google">
                <span>🌐</span>
                <span>Google登录</span>
              </button>
              <button type="button" class="social-btn github">
                <span>🐙</span>
                <span>GitHub登录</span>
              </button>
            </div>
            
            <div class="register-link">
              还没有账户？<a href="/register-verify">立即注册</a>
            </div>
          </form>
        </div>
      </div>
    </div>
    
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
  </div>
</template>

<script>
import axios from '@/utils/request'

export default {
  name: 'UserLogin',
  data() {
    return {
      username: '',
      password: '',
      rememberMe: false,
      loading: false,
      error: ''
    }
  },
  methods: {
    async handleLogin() {
      this.loading = true
      this.error = ''
      try {
        // 使用URLSearchParams格式化表单数据
        const params = new URLSearchParams()
        params.append('username', this.username)
        params.append('password', this.password)
        
        // 发送登录请求到正确的端口
        const res = await axios.post('/auth/login', params, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          // 确保不会被重定向
          maxRedirects: 0
        })
        
        console.log('登录返回：', res.data)
        
        // 关键修复：根据后端实际返回结构解析（后端用success字段判断成功与否）
        if (res.data.success) {
          const token = res.data.data?.token
          const roleId = res.data.data?.roleId
          if (token && roleId) {
            // 存储token到localStorage
            localStorage.setItem('token', token)
            // 存储用户信息（可选，便于后续使用）
            localStorage.setItem('userInfo', JSON.stringify(res.data.data))
            
            console.log('Token已存储:', token)
            
            // 立即设置axios默认请求头，确保后续请求能使用token
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + token
            
            // 根据roleId跳转到对应角色的首页
            switch (roleId) {
              case 1: // 管理员
                this.$router.push('/admin')
                break
              case 2: // 教师
                this.$router.push('/teacher')
                break
              case 3: // 学生
                this.$router.push('/student')
                break
              default:
                this.$router.push({ name: 'home' })
            }
          } else {
            this.error = '登录失败，未获取到token或角色信息'
          }
        } else {
          // 后端返回失败状态时
          this.error = res.data.message || '登录失败，请检查用户名和密码'
        }
      } catch (e) {
        // 处理可能的重定向到HTML登录页面的情况
        if (e.response && e.response.status === 200 && 
            e.response.headers['content-type'] && 
            e.response.headers['content-type'].includes('text/html')) {
          this.error = '登录接口返回了错误的响应格式，请检查后端配置'
        } else if (e.response && e.response.status === 403) {
          this.error = '访问被拒绝，请检查后端安全配置'
        } else {
          // 网络错误或服务器异常时
          this.error = e.response?.data?.message || '登录失败，请稍后重试'
        }
        console.error('登录错误:', e)
      } finally {
        this.loading = false
      }
    }
  },
  created() {
    // 页面加载时自动设置token到请求头（如果已登录）
    const token = localStorage.getItem('token')
    if (token) {
      // token已经存储在localStorage中，axios拦截器会自动添加到请求头
      axios.defaults.headers.common['Authorization'] = 'Bearer ' + token
      console.log('已登录用户，token:', token)
    }
    
    // 如果记住我功能启用，尝试从localStorage获取用户名
    const savedUsername = localStorage.getItem('savedUsername')
    if (savedUsername) {
      this.username = savedUsername
      this.rememberMe = true
    }
  },
  watch: {
    rememberMe(newVal) {
      if (!newVal) {
        localStorage.removeItem('savedUsername')
      }
    }
  }
}
</script>

<style scoped lang="scss">
.login-wrapper {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.login-wrapper::before {
  content: "";
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
  transform: rotate(30deg);
}

.login-container {
  display: flex;
  width: 900px;
  height: 550px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 1;
}

.login-left {
  flex: 1;
  background: linear-gradient(135deg, #43cea2 0%, #185a9d 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.welcome-section h1 {
  font-size: 2.2rem;
  margin-bottom: 20px;
  font-weight: 700;
}

.welcome-section p {
  font-size: 1.1rem;
  margin-bottom: 30px;
  line-height: 1.6;
  opacity: 0.9;
}

.features-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 80px;
}

.feature-icon {
  font-size: 2rem;
  margin-bottom: 10px;
}

.feature-item span {
  font-size: 0.9rem;
  text-align: center;
}

.login-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.login-form-container {
  width: 100%;
  max-width: 350px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  font-size: 2rem;
  color: #333;
  margin-bottom: 10px;
}

.login-header p {
  color: #666;
  font-size: 1rem;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 15px;
  font-size: 1.2rem;
  z-index: 1;
}

input {
  width: 100%;
  padding: 15px 15px 15px 50px;
  border: 2px solid #e1e5ee;
  border-radius: 10px;
  font-size: 1rem;
  transition: all 0.3s ease;
  background: #f8f9fa;
}

input:focus {
  border-color: #409eff;
  outline: none;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.2);
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.forgot-password {
  color: #409eff;
  text-decoration: none;
  font-size: 0.9rem;
}

.forgot-password:hover {
  text-decoration: underline;
}

.login-button {
  width: 100%;
  padding: 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.login-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.login-button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.loading-spinner {
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner::after {
  content: "";
  width: 16px;
  height: 16px;
  margin-left: 10px;
  border: 2px solid #ffffff;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.divider {
  display: flex;
  align-items: center;
  margin: 25px 0;
}

.divider::before,
.divider::after {
  content: "";
  flex: 1;
  border-bottom: 1px solid #e1e5ee;
}

.divider span {
  padding: 0 15px;
  color: #666;
  font-size: 0.9rem;
}

.social-login {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 25px;
}

.social-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 12px;
  border-radius: 10px;
  border: 2px solid #e1e5ee;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.social-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.social-btn.google:hover {
  border-color: #db4437;
}

.social-btn.github:hover {
  border-color: #333;
}

.register-link {
  text-align: center;
  color: #666;
  font-size: 0.95rem;
}

.register-link a {
  color: #409eff;
  text-decoration: none;
  font-weight: 500;
}

.register-link a:hover {
  text-decoration: underline;
}

.error-message {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: #f56c6c;
  color: white;
  padding: 15px 30px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  animation: slideDown 0.3s ease;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translate(-50%, -20px);
  }
  to {
    opacity: 1;
    transform: translate(-50%, 0);
  }
}

@media (max-width: 992px) {
  .login-container {
    width: 95%;
    height: auto;
  }
  
  .login-left {
    display: none;
  }
}

@media (max-width: 576px) {
  .login-container {
    flex-direction: column;
    border-radius: 15px;
  }
  
  .login-right {
    padding: 30px 20px;
  }
  
  .login-form-container {
    max-width: 100%;
  }
}
</style>